/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package th.stripes.action;

import able.stripes.JSP;
import com.google.inject.Inject;
import com.oas.thit._this.profile.depositor.xsd.DepositorProfileResponseBody;
import com.oas.thit._this.xsd.THISBaseDataElementBody;
import com.oas.thit.xmlmessage.xsd.Header;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import javax.xml.bind.JAXBElement;
import net.sourceforge.stripes.action.FileBean;
import net.sourceforge.stripes.action.RedirectResolution;
import net.sourceforge.stripes.action.Resolution;
import net.sourceforge.stripes.action.StreamingResolution;
import net.sourceforge.stripes.action.UrlBinding;
import net.sourceforge.stripes.security.action.Secure;
import net.sourceforge.stripes.validation.Validate;
import net.sourceforge.stripes.validation.ValidateNestedProperties;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import th.dao.JadualPenerbanganDAO;
import th.dao.KodStatusDAO;
import th.dao.KodUrusanDAO;
import th.dao.PengiklananDAO;
import th.dao.THISutilDAO;
import th.manager.AdminManager;
import th.manager.InfoPetugasManager;
import th.manager.ResponseManager;
import th.manager.RetrieveSmsInfoManager;
import th.manager.SMSBulkManager;
import th.manager.SMSgatewayManager;
import th.manager.SejarahTransaksiManager;
import th.manager.UserManager;
import th.model.InfoAudit;
import th.model.InfoPetugas;
import th.model.JadualPenerbangan;
import th.model.Pengguna;
import th.model.Pengiklanan;
import th.model.SejarahTransaksi;
import th.model.Sms;
import th.stripes.BaseActionBean;
import th.stripes.Configuration;
import th.stripes.config.AuthRequired;
import th.stripes.util.DateConverter;
import th.stripes.webservice.WebServiceUtil;

/**
 *
 * @author fikri
 */
@UrlBinding("/admin")
public class AdminAction extends BaseActionBean{
    
    private Pengguna pengguna;    
    private String noAkaun;
    private String passbook;    
    
    private String tarikhPenghantaran;
    
    private FileBean file;
    
    private List<Pengiklanan> senaraiIklan;
    
    private Pengiklanan iklan;
    
    private List<Map <String,String>> senaraiBH = new ArrayList<Map<String,String>>();
    
    private static String SUCCESSFUL="0000";
    private static String SYSTEM_ERROR = "9999";
    private static String PROFILE_ENQ_MSG_ID = "TPDPPROFWD01";
    private static String HEADER_ID_PROFILE_ENQUIRY = "THSDPQR"; 
    private static String USER_ACCTIVE_MSG_ID ="TPUSRMGTWD00";
    private static Logger LOG = LoggerFactory.getLogger(DepositActionBean.class);
    
    @ValidateNestedProperties({ 
        @Validate(field="trhMula", converter=DateConverter.class),
        @Validate(field="trhTamat", converter=DateConverter.class)
    }) 
    private JadualPenerbangan jadual;
    
    private InfoPetugas infoPetugas;
    
    @Inject UserManager userManager;
    
    @Inject AdminManager adminManager;
    
    @Inject JadualPenerbanganDAO jadualPenerbanganDAO;
    
    @Inject private WebServiceUtil webUtil; 
    
    @Inject private THISutilDAO tHISutilDAO;
    
    @Inject private SMSgatewayManager sMSgatewayManager;
    
    @Inject private ResponseManager responseManager;
    
    @Inject private InfoPetugasManager infoPetugasManager;
    
    @Inject private KodUrusanDAO kodUrusanDAO;
    
    @Inject private KodStatusDAO kodStatusDAO;
    
    @Inject PengiklananDAO pengiklananDAO;
    
    @Inject private SejarahTransaksiManager sejarahTransaksiManager;
    
    @Inject private RetrieveSmsInfoManager smsInfoManager;
    
    @Inject private SMSBulkManager smsBulkManager;
    
    @Inject Configuration conf;
    
    private String fileName;
    
    private List<InfoPetugas> senaraiPetugas;
    
    private List<Sms> senaraiSms;
    
    
    @AuthRequired
    @Secure(roles="ADMIN")
    public Resolution showTambahPenggunaDalamanForm() {
        return new JSP("admin/tambah_pguna.jsp");
    }   
    
    @AuthRequired
    @Secure(roles="ADMIN")
    public Resolution showDeactivateSearchForm() {
        return new JSP("admin/search_deactivate_user.jsp");
    }
    
    public Resolution showPetugasForm() {
        senaraiPetugas = infoPetugasManager.getSenaraiPetugas();
        return new JSP("admin/info_petugas_main_form.jsp");
    }
    
    public Resolution showSmsManualForm() {        
        return new JSP("admin/manual_sms_form.jsp");
    }
    
    public Resolution sendSmsManual() {   
        if (StringUtils.isNotBlank(fileName)) {
            String ARCHIVE_DIR = conf.getProperty("sms.arc.dir");
            String path = ARCHIVE_DIR + (ARCHIVE_DIR.endsWith(File.separator) ? "" : File.separator) + fileName;
            File f = new File(path);
            if (f.exists()) {
                File[] files = new File[1];
                files[0] = f;
                smsBulkManager.sendSmsManual(files);
            }            
        }
        
        return new JSP("admin/manual_sms_form.jsp");
    }
    
    public Resolution showSmsInfoManualForm() {        
        return new JSP("admin/manual_sms_info_form.jsp");
    }
    
    public Resolution semakFileForm() {      
        
        List<String> listOfKT = new ArrayList<String>();
        Map<String, Map<String, String>> parent = new HashMap<String, Map<String, String>>();
        
        Map<String, String> child = new HashMap<String, String>();
        
        if (file != null) {
            try {
                Scanner scan = new Scanner(file.getInputStream()).useDelimiter("\n");
                while (scan.hasNext()) {
                    String content = scan.next();
                        if (StringUtils.isBlank(content)) {
                            continue;
                        }
                        LOG.info("content {}", content);
                        String[] f = content.split("\\$\\$");
                        String currKT = f[0].toString();
                        String noTel = f[3].toString();
                        String laporDt = f[7].toString();
                        String lapotTpt = f[8].toString();
                        String laporTime = f[9].toString();
                        String laporWaktu = f[10].toString();
                        
                        Map<String,String> map = new HashMap<String,String>();
                        map.put("KT", currKT);
                        map.put("noTel", noTel);
                        map.put("laporDt", laporDt);
                        map.put("lapotTpt", lapotTpt);
                        map.put("laporTime", laporTime);
                        map.put("laporWaktu", laporWaktu);
                        
                        
                         if (ArrayUtils.contains(listOfKT.toArray(), currKT)) {
                            Map<String, String> m = parent.get(currKT);
                                if (m != null) {
                                    StringBuilder noPhone = new StringBuilder(m.get("phones"));
                                    if (noPhone.length() > 0) {
                                        noPhone.append(",");
                                    }
                                    noPhone.append(noTel);

                                    parent.get(currKT).put("phones", noPhone.toString());
                                }
                            } else {
                                child = new HashMap<String, String>();
                                child.put("phones", noTel);                                
                                parent.put(currKT, child);
                                listOfKT.add(currKT);
                            }                        
                        senaraiBH.add(map); 
                }
                
                if (parent.size() > 0) {
                    for (Map.Entry<String, Map<String, String>> m : parent.entrySet()) {
                        Map<String, String> value = m.getValue();
                        if (value != null) {                            
                            String phonesNo = value.get("phones");
                            LOG.debug("phones {} ", phonesNo);
                            
                        }
                    }
                }
                String ARCHIVE_DIR = conf.getProperty("sms.arc.dir");
                fileName = file.getFileName();
                String path = ARCHIVE_DIR + (ARCHIVE_DIR.endsWith(File.separator) ? "" : File.separator) + fileName;
                File f = new File(path);
                file.save(f);
                
            } catch (Exception ex ) {
            }
            
        }
        
        return new JSP("admin/manual_sms_form.jsp");
    }
    
    public Resolution searchSms() {
        senaraiSms = smsInfoManager.getSenaraiSmsWithoutInfo(tarikhPenghantaran);
        return new JSP("admin/manual_sms_info_form.jsp");
    }
    
    public Resolution getSmsInfo() {
        senaraiSms = smsInfoManager.getSenaraiSmsWithoutInfo(tarikhPenghantaran);
        if (!senaraiSms.isEmpty()) {
            if (smsInfoManager.doGetSmsInfoManual(senaraiSms)) {
                addSimpleMessage("Pengambilan berjaya. Sila semak di laporan penghantaran SMS.");
            } else {
                addSimpleError("Tidak dapat mengambil status penghantaran daripada Macro Kiosk. Sila cuba sekali lagi.");
            }
        }
        senaraiSms = null;
        return new JSP("admin/manual_sms_info_form.jsp");
    }
    
    
    public Resolution showEditAddPetugasForm() {
        
        String idPetugas = getContext().getRequest().getParameter("id");
        if (StringUtils.isNotBlank(idPetugas)) {
            infoPetugas = infoPetugasManager.getPetugasById(idPetugas);
        }
        
        return new JSP("admin/info_petugas_edit_form.jsp");
    }
    
    public Resolution tambahPetugas() {
        pengguna = getContext().getCurrentUser();
        if (infoPetugas != null) {      
            if ( StringUtils.isNotBlank(infoPetugas.getNoTel()) && !infoPetugas.getNoTel().startsWith("6")) {
                infoPetugas.setNoTel("6" + infoPetugas.getNoTel());
            }
            infoPetugasManager.savePetugas(infoPetugas);            
            addSimpleMessage("Kemasukan Berjaya");
        } else {
            addSimpleError("Kemasukan Gagal.");
        }       
        
        return new RedirectResolution(AdminAction.class, "showPetugasForm");
    }
    
     public Resolution padamPetugas() {
         
        String idPetugas = getContext().getRequest().getParameter("id");
        if (StringUtils.isNotBlank(idPetugas)) {
            infoPetugas = infoPetugasManager.getPetugasById(idPetugas);
            if (infoPetugas != null) {
                addSimpleMessage("Hapus Berjaya");
                infoPetugasManager.deletePetugas(infoPetugas);
            }
        }
        
       return new RedirectResolution(AdminAction.class, "showPetugasForm");
    }
    
    public Resolution searchInactivateUser() {
       
        Pengguna pguna = userManager.findUser(pengguna.getNoKp(), noAkaun);       
        pengguna.setNama(pguna.getNama());
        if (pguna != null) {
            if (pguna.getActive() == 'Y'){
                addSimpleError("Pengguna masih lagi aktif!");
                return new JSP("admin/search_deactivate_user.jsp");
            } 
        } else {            
            addSimpleError("Pengguna tidak dijumpai!");
        }
        return new JSP("admin/activate_user.jsp");
    }
    
    public Resolution activateUser() {
       
        Pengguna pguna = userManager.findUser(pengguna.getNoKp(), noAkaun);       
        
        if (pguna != null) {
            
//            
//            ia.setDiKemaskiniOleh(getContext().getCurrentUser());
//            ia.setTarikhKemaskini(new Date());
//            pguna.setInfoAudit(ia);        
            
            try { // Call Web Service Operation
                com.oas.thit._this.services.THISServices service = new com.oas.thit._this.services.THISServices();
                com.oas.thit._this.services.THISServicesPortType port = service.getTHISServicesHttpSoap11Endpoint();
                // TODO initialize WS operation arguments here
                com.oas.thit._this.xsd.THISRequest req = new com.oas.thit._this.xsd.THISRequest();
                com.oas.thit._this.xsd.ObjectFactory objFactory = new com.oas.thit._this.xsd.ObjectFactory();

                req.setHeader( webUtil.createHeader(PROFILE_ENQ_MSG_ID, HEADER_ID_PROFILE_ENQUIRY) );

                THISBaseDataElementBody reqBody = objFactory.createTHISBaseDataElementBody();
                reqBody.setTHAcct(objFactory.createTHISBaseDataElementBodyTHAcct(noAkaun));
                reqBody.setTHICNo(objFactory.createTHISBaseDataElementBodyTHICNo(pengguna.getNoKp()));

                JAXBElement<THISBaseDataElementBody> jReqBody =  objFactory.createTHISRequestBody(reqBody);
                req.setBody(jReqBody);

                // TODO process result here
                com.oas.thit._this.profile.depositor.xsd.DepositorProfileResponse result = port.depositorProfileQuery(req);
                Header header = result.getHeader().getValue();
                String responseCode = header.getResponseCode().getValue();
                SejarahTransaksi sejarahTransaksi = new SejarahTransaksi();
                if (responseCode.equals(SUCCESSFUL)) {
                    DepositorProfileResponseBody resp = result.getBody().getValue();
                    if (resp != null) {
                        
                    if(!resp.getTHPassbookNo().getValue().equals(passbook)){
                        addSimpleError("No. Siri Buku yang dimasukkan tidak sah. Sila cuba lagi"); 
                        return new JSP("admin/activate_user.jsp");
                    }
                        
                        String mPhone = resp.getTHPhoneMobile().getValue().trim();
//                        if (StringUtils.isNotBlank(mPhone)) {
                            String generatedPassword = generatePasswordAuto();
//                            pengguna = userManager.findUser(pengguna.getNoKp(), null);
//                            if (pguna != null) {                            
                                StringBuilder sb = new StringBuilder("e-THiJARI: Kemaskini kata laluan. ");
                                sb.append("Kata Laluan adalah ").append(generatedPassword).append(". Tidak melakukan transaksi? Hubungi THCC ");
                                sb.append(tHISutilDAO.findById("101").getDeskripsi().toString());
                                String rcode = sMSgatewayManager.sendSMS(mPhone, sb.toString());
                                
                                sejarahTransaksi.setPengguna(pengguna);
                                sejarahTransaksi.setTrhMasuk(new Date());
                                sejarahTransaksi.setUrusan(kodUrusanDAO.findById(USER_ACCTIVE_MSG_ID));
                                sejarahTransaksi.setIdSessi(getContext().getRequest().getSession().getId());                                
                                sejarahTransaksi.setNilaiDalaman1(header.getTxid().getValue().trim());
                                
                                if (rcode.equals("200")) { 
                                    pguna.setBilanganCubaan(new Integer(0));
                                    pguna.setActive(pengguna.getActive());
                                    pguna.setPassword(encrypt(generatedPassword));
                                    InfoAudit ia = pguna.getInfoAudit();
                                    ia = pguna.getInfoAudit();
                                    ia.setDiKemaskiniOleh(pguna);
                                    ia.setTarikhKemaskini(new Date());
                                    pguna.setInfoAudit(ia);                                    
                                    userManager.updatePengguna(pguna);
                                    sejarahTransaksi.setStatus(kodStatusDAO.findById("0000"));
                                    addSimpleMessage("Kemaskini Berjaya. Kata laluan telah di hantar ke telefon bimbit pengguna.");
                                } else {
                                    sejarahTransaksi.setStatus(kodStatusDAO.findById("9999"));
                                    addSimpleError("Terdapat masalah pada sistem. Sila cuba sekali lagi.");
                                }
                                sejarahTransaksiManager.saveSejarahTransaksi(sejarahTransaksi); 

//                            } else {
//                                addSimpleError("No pengenalan tidak wujud.");
//                                return new JSP("pguna/lupa_kata_laluan.jsp");
//                            }
//                        } 
//                        else {
//                            addSimpleError("Pengguna tidak mempunyai no. telefon bimbit. Pengaktifan semula tidak berjaya dilakukan");
//                        }                    
                    }
                } else {
                addSimpleError(responseManager.getResponseMessage(responseCode, PROFILE_ENQ_MSG_ID));
            }
        } catch (Exception ex) {
            LOG.error("ex {}", ex);
            addSimpleError(ex.getMessage());
        }
        return new JSP("admin/msg.jsp");    
        } else {            
            addSimpleError("Pengguna tidak dijumpai!");
        }
        return new JSP("admin/msg.jsp");
    }
    
    public Resolution addUser() {
        
        if (validate()) {
            addSimpleError("Pengguna telah wujud.");
            return new JSP("admin/tambah_pguna.jsp");
        } else {
            InfoAudit ia = new InfoAudit();
            ia.setDimasukOleh(pengguna);
            ia.setTarikhMasuk(new Date());
            pengguna.setInfoAudit(ia);
            pengguna.setActive('Y');
            String ecrypt = encrypt(pengguna.getPassword());
            pengguna.setPassword(ecrypt);
            //added in 2/6/2015
            pengguna.setSecPhrase(pengguna.getSecPhrase());
            
            userManager.updatePengguna(pengguna);           
            
            addSimpleMessage("Kemasukan Berjaya.");
        }        
        
        return new JSP("admin/msg.jsp");
    }
    
    @AuthRequired
    @Secure(roles="ADMIN,JABATAN HAJI")
    public Resolution showJadualPenerbanganAdminForm() {
        return new JSP("admin/tarikh_penerbangan.jsp");
    }
    
    public Resolution saveJadualPenerbangan() {
         JadualPenerbangan jp = jadualPenerbanganDAO.findById(jadual.getTahunHijrah());         
         pengguna = getContext().getCurrentUser();
         InfoAudit ia = new InfoAudit();
         if (jp != null) {
             ia = jp.getInfoAudit();
             ia.setDiKemaskiniOleh(pengguna);
             ia.setTarikhKemaskini(new Date());             
         } else {
             ia.setDimasukOleh(pengguna);
             ia.setTarikhMasuk(new Date());
         }
         jp.setInfoAudit(ia);
         jp.setTahunMasihi(jadual.getTahunMasihi());
         jp.setTrhMula(jadual.getTrhMula());
         jp.setTrhTamat(jadual.getTrhTamat());
        
         adminManager.save(jp);  
         
         SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
         Calendar s = Calendar.getInstance();
         s.setTime(jadual.getTrhMula());
         s.add(Calendar.DATE, -2);
         Calendar f = Calendar.getInstance();
         f.setTime(jadual.getTrhTamat());
         f.add(Calendar.DATE, -2);
         
         StringBuilder sb = new StringBuilder("Sms peringantan penerbangan kepada jemaah akan mula dihantar pada ")
                 .append(sdf.format(s.getTime()))
                 .append(" dan berakhir pada ")
                 .append(sdf.format(f.getTime()));
         
         addSimpleMessage(sb.toString());
         return new JSP("admin/tarikh_penerbangan_info.jsp");
    }
    
    public Resolution searchJadual() {        
        String delim = "__^$__";
        SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
        StringBuilder result = new StringBuilder();
        String tahunHijrah = getContext().getRequest().getParameter("hijrah");
        
        jadual = jadualPenerbanganDAO.findById(tahunHijrah);        
        
        if (jadual != null){
            result.append(jadual.getTahunMasihi())
                    .append(delim)
                    .append(sdf.format(jadual.getTrhMula()))
                    .append(delim)
                    .append(sdf.format(jadual.getTrhTamat()));
        }
        
        return new StreamingResolution("text/plain", result.toString());
    }
    
    @AuthRequired
    @Secure(roles="ADMIN")
    public Resolution showFormIklan() {
        senaraiIklan = pengiklananDAO.findAll();
        return new JSP("admin/iklan_search_form.jsp");
    }
    
    @AuthRequired
    @Secure(roles="ADMIN")
    public Resolution showFormAddIklan() {
        return new JSP("admin/iklan_new_form.jsp");
    }
    
    @AuthRequired
    @Secure(roles="ADMIN")
    public Resolution showFormEditIklan() {
        return new JSP("admin/iklan_edit_form.jsp");
    }
    
    @AuthRequired
    @Secure(roles="ADMIN")
    public Resolution editIklan() {
        String id = getContext().getRequest().getParameter("id");
        if (StringUtils.isNotBlank(id)) {
            iklan = pengiklananDAO.findById(Integer.parseInt(id));
        }
        return new JSP("admin/iklan_edit_form.jsp");
        //return new RedirectResolution(AdminAction.class, "showFormEditIklan");
    }
    
    //added by hasnor
    @AuthRequired
    @Secure(roles="ADMIN")
    public Resolution deleteIklan() {
        String id = getContext().getRequest().getParameter("id");
        if (StringUtils.isNotBlank(id)) {
            iklan = pengiklananDAO.findById(Integer.parseInt(id));
            if (iklan != null) {
                adminManager.deleteIklan(iklan);
                senaraiIklan = pengiklananDAO.findAll();
                addSimpleMessage("Rekod berjaya di padam");
            } else {
                addSimpleMessage("Rekod tidak berjaya di padam");
            }
        } 
        
        //return new JSP("admin/iklan_search_form.jsp");
        return new RedirectResolution(AdminAction.class, "showFormIklan");
    }
    
    @AuthRequired
    @Secure(roles="ADMIN")
    public Resolution tambahIklan() {
        pengguna = getContext().getCurrentUser();
        if (iklan != null) {
            InfoAudit ia = new InfoAudit();
            ia.setDimasukOleh(pengguna);
            ia.setTarikhMasuk(new Date());
            iklan.setInfoAudit(ia);
            adminManager.saveIklan(iklan);      
            senaraiIklan = pengiklananDAO.findAll();
            addSimpleMessage("Kemasukan Berjaya");
        } else {
            addSimpleError("Kemasukan Gagal.");
        }       
        
        //return new JSP("admin/iklan_search_form.jsp");
        return new RedirectResolution(AdminAction.class, "showFormIklan");
    }
    
    private boolean validate () {
        return  ( userManager.findUser( pengguna.getNoKp(), null) != null ? true : false );        
    }

    public Pengguna getPengguna() {
       return pengguna;
    }

    public void setPengguna(Pengguna pengguna) {
        this.pengguna = pengguna;
    }

    public JadualPenerbangan getJadual() {
        return jadual;
    }

    public void setJadual(JadualPenerbangan jadual) {
        this.jadual = jadual;
    }

    public String getNoAkaun() {
        return noAkaun;
    }

    public void setNoAkaun(String noAkaun) {
        this.noAkaun = noAkaun;
    }
    
    public String getPassbook() {
        return passbook;
    }

    public void setPassbook(String passbook) {
        this.passbook = passbook;
    }

    public List<Pengiklanan> getSenaraiIklan() {
        return senaraiIklan;
    }

    public void setSenaraiIklan(List<Pengiklanan> senaraiIklan) {
        this.senaraiIklan = senaraiIklan;
    }

    public Pengiklanan getIklan() {
        return iklan;
    }

    public void setIklan(Pengiklanan iklan) {
        this.iklan = iklan;
    }

    public List<InfoPetugas> getSenaraiPetugas() {
        return senaraiPetugas;
    }

    public void setSenaraiPetugas(List<InfoPetugas> senaraiPetugas) {
        this.senaraiPetugas = senaraiPetugas;
    }

    public InfoPetugas getInfoPetugas() {
        return infoPetugas;
    }

    public void setInfoPetugas(InfoPetugas infoPetugas) {
        this.infoPetugas = infoPetugas;
    }

    public FileBean getFile() {
        return file;
    }

    public void setFile(FileBean file) {
        this.file = file;
    }

    public List<Map<String, String>> getSenaraiBH() {
        return senaraiBH;
    }

    public void setSenaraiBH(List<Map<String, String>> senaraiBH) {
        this.senaraiBH = senaraiBH;
    }

    public String getTarikhPenghantaran() {
        return tarikhPenghantaran;
    }

    public void setTarikhPenghantaran(String tarikhPenghantaran) {
        this.tarikhPenghantaran = tarikhPenghantaran;
    }

    public List<Sms> getSenaraiSms() {
        return senaraiSms;
    }

    public void setSenaraiSms(List<Sms> senaraiSms) {
        this.senaraiSms = senaraiSms;
    }

    public String getFileName() {
        return fileName;
    }

    public void setFileName(String fileName) {
        this.fileName = fileName;
    }
}
